package com.sunzhe.cms.config;

import cn.hutool.core.date.DateUtil;
import com.ibeetl.admin.core.entity.CoreLog;
import com.ibeetl.admin.core.service.CoreLogService;
import com.ibeetl.admin.core.service.CoreUserService;
import com.ibeetl.admin.core.util.HttpRequestLocal;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.cms.entity.CmsArticle;
import com.ibeetl.cms.service.CmsArticleService;
import org.apache.commons.lang3.math.NumberUtils;
import org.beetl.core.GroupTemplate;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 用于配置关于访问文章页面的拦截器，用于访问记录
 * @author Administrator
 *
 */
@Configuration
public class ArticleLogInterceptorConf implements WebMvcConfigurer, InitializingBean {

    // 开发用的模拟当前用户和机构
    Long useId;

    Long orgId;

    String mvcTestPath;

    @Autowired
    Environment env;

    @Autowired
    CoreUserService userService;

    @Autowired
    BeetlGroupUtilConfiguration beetlGroupUtilConfiguration;

    @Autowired
    HttpRequestLocal httpRequestLocal;
    
    @Autowired
    CmsArticleService articleService;
    
    @Autowired
	CoreLogService logService;

    @Autowired
    GroupTemplate groupTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	registry.addInterceptor(new ArticleLogInterceptor(httpRequestLocal,this)).addPathPatterns("/article.do");
        // super.addInterceptors(registry);

    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new DateFormatter("yyyy-MM-dd HH:mm:ss"));
        registry.addFormatter(new DateFormatter("yyyy-MM-dd"));
    }


    @Override
    public void afterPropertiesSet() throws Exception {
    }


}

@Configuration
class ArticleLogInterceptor implements HandlerInterceptor {

    ArticleLogInterceptorConf conf;
    HttpRequestLocal httpRequestLocal;

    public ArticleLogInterceptor(HttpRequestLocal httpRequestLocal, ArticleLogInterceptorConf conf) {
        this.conf = conf;
        this.httpRequestLocal = httpRequestLocal;
    }
/**
 * 
preHandle：在业务处理器处理请求之前被调用。预处理，可以进行编码、安全控制、权限校验等处理；
postHandle：在业务处理器处理请求执行完成后，生成视图之前执行。后处理（调用了Service并返回ModelAndView，但未进行页面渲染），有机会修改ModelAndView （这个博主就基本不怎么用了）；
afterCompletion：在DispatcherServlet完全处理完请求后被调用，可用于清理资源等。返回处理（已经渲染了页面）；
 */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
    	//System.out.println("preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    	String articleId = request.getParameter("id");
    	CmsArticle article = conf.articleService.queryById(NumberUtils.toLong(articleId));
    	if (article == null) {
            request.setAttribute("redirect","");
            throw new PlatformException("参数错误");
        }
    	String type = "visit";
    	Long onehour = 3600*1000L;
    	boolean isValidate = false;
    	
		String ip = httpRequestLocal.getRequestIP();
		
		Long time = new Date().getTime() - onehour;
		
		String strTime = DateUtil.format(new Date(time), "yyyy-MM-dd HH:mm:ss");
		
		Integer validateLog = conf.logService.validateLog(article.getId(), strTime, ip, type);
		
		
		if (isValidate == false ||validateLog == null || validateLog == 0) {
			CoreLog log = new CoreLog();
	    	log.setArticleId(article.getId());
	    	log.setCreateTime(new Date());
	    	log.setIp(httpRequestLocal.getRequestIP());
	    	conf.logService.upsert(log);
		}
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    	//System.out.println("afterCompletion");
    }

}
